<script setup lang="ts">
import {message} from "ant-design-vue";
import LineTextArea from "~/contentScripts/views/wxt/components/LineTextArea.vue";

// 投放地域
import {WxtBizCode, WxtTemplateType, WxtUtils} from "~/contentScripts/views/wxt/lib/wxtUtils";
import PlacementAreaResultTable
  from "~/contentScripts/views/wxt/SuperOptimization/KeywordPromotion/PlacementArea/PlacementAreaResultTable.vue";
import WxtModal from "~/contentScripts/views/wxt/wxt-modal.vue";

const props = defineProps({
  rows: {
    type: Array,
    default: () => []
  },
  bizCode: {
    type: String as PropType<WxtBizCode>,
    default: WxtBizCode.关键字推广,
  },
});
const visible = ref(false);
const templates = ref<any[]>([]);
3
const areas = ref<any[]>([]);
const handle = () => {
  if (props.rows.length === 0) {
    message.error("请选择需要批量处理的数据！");
    return;
  }
  WxtUtils.getAreaCodeConfig(props.bizCode).then(res => {
    areas.value = res;
  })
  WxtUtils.templateFindList(WxtTemplateType.AREA, props.bizCode).then(res => {
    templates.value = res.data.data.list;
  })
  visible.value = true;
};
const areaInput = ref('');
// 解析类型 省份 城市
const parseTypes = [
  {
    label: '解析为省份',
    value: 'province',
  },
  {
    label: '解析为城市',
    value: 'city',
  },
];
const parseType = ref(parseTypes[0].value);
const choseTemplate = (value: string) => {
  templates.value.map((t: any) => {
    if (t.templateId === value) {
      parseType.value = 'city';
      const ids: string[] = JSON.parse(t.templateValue);
      areaInput.value = getNames(ids).join('\n');
    }
  })
};
const results = ref<{ tableName: string, name: string, id: number, index: number }[]>([]);
const getNames = (ids: string[]): string[] => {
  const names: string[] = [];
  for (let i = 0; i < ids.length; i++) {
    areas.value.forEach((a: any) => {
      if (a.id === parseInt(ids[i]) || a.provinceId === parseInt(ids[i])) {
        if (names.includes(a.name)) {
          return;
        }
        names.push(a.name);
      }
    })
  }
  return names;
};
const templateId = ref(undefined);
watch(() => areaInput.value, (v) => {
  if (v === '') {
    results.value = [];
  } else {
    const data = areaInput.value.split('\n');
    let areaChecked = areas.value.filter((area) => {
      if (parseType.value === 'province') {
        return data.includes(area.provinceName)
      } else if (parseType.value === 'city') {
        return data.includes(area.name);
      }
    });
    let d: any[] = [];
    d = areaChecked.map((area) => {
      if (parseType.value === 'province') {
        return {
          tableName: '省份',
          name: area.provinceName,
          id: area.provinceId,
        }
      } else {
        return {
          tableName: '城市',
          name: area.name,
          id: area.id,
        }
      }
    });
    // 将d中id重复的去除只保留一个
    const uniqueIds: any = {};  // 用于存储唯一的 ID
    d = d.reduce((result, obj) => {
      if (!uniqueIds[obj.id]) {  // 如果 ID 在 uniqueIds 中不存在
        uniqueIds[obj.id] = true; // 将 ID 添加到 uniqueIds 中
        result.push(obj); // 将对象添加到结果数组中
      }
      return result;
    }, []);
    d.map((item, index) => {
      item.index = index + 1;
    });
    results.value = d;
  }
});
const del = (items: any[]) => {
  items.map((item) => {
    const input = areaInput.value.split('\n');
    input.splice(input.indexOf(item.name), 1);
    areaInput.value = input.join('\n');
  })
}
watch(() => templateId.value, (v) => {
  if (v === '') {
    areaInput.value = '';
  }
});
const update = () => {
  const campaignIds: string[] = props.rows.map((r: any) => r.campaignId);
  WxtUtils.advancedBatchUpdate([
    ...campaignIds.map((campaignId: string) => ({
      campaignId,
      launchAreaStrList: results.value.map((item)=>item.id),
    })),
  ],props.bizCode).then(res => {
    visible.value = false;
    if (res.data.info.ok !== true) {
      message.error(res.data.info.message)
      return;
    }
    message.success("设置地域成功！");
  }).finally(() => {
    results.value = [];
  });
};
</script>

<template>
  <div @click="handle">
    <slot>
      <a-button size="small" type="primary" ghost>投放地域</a-button>
    </slot>
  </div>
  <wxt-modal title="设置地域" v-model:visible="visible" :width="1200" :style="{
    top: '20px',
  }"
  >
    <a-row style="padding-bottom: 10px;">
      <a-space>
        <a-select v-model:value="parseType" style="width: 120px;"
                  :disabled="typeof templateId!=='undefined'"
        >
          <a-select-option v-for="item in parseTypes" :key="item.value" :value="item.value">{{ item.label }}
          </a-select-option>
        </a-select>
        <div>
          地域模版：
          <a-select v-model:value="templateId" @change="choseTemplate" style="width: 200px;"
                    placeholder="选择地域模版" allow-clear
          >
            <a-select-option v-for="item in templates" :key="item.templateId" :value="item.templateId">
              {{ item.templateName }}
            </a-select-option>
          </a-select>
        </div>
      </a-space>
    </a-row>
    <a-row type="flex" style="height: calc(100vh - 300px);">
      <a-col style="height: 100%;overflow-y: hidden;">
        <LineTextArea v-model:value="areaInput" style="width: 180px;height: 100%;"/>
      </a-col>
      <a-col style="display: flex;align-items:center;padding: 10px;font-size: 12px;color: #666;">
        >>
      </a-col>
      <a-col flex="1" style="overflow-x: hidden;">
        <PlacementAreaResultTable :result="results" @delete="del" :parse-type="parseType"/>
      </a-col>
    </a-row>
    <a-divider/>
    <a-row type="flex" style="text-align: right;">
      <a-col flex="1"/>
      <a-col>
        <a-space>
          <a-button type="default" @click="visible=false">取消</a-button>
          <a-button type="primary" @click="update">确定</a-button>
        </a-space>
      </a-col>
    </a-row>
  </wxt-modal>
</template>

<style scoped>

</style>
